package com.web.admin.web.base.core;

import com.blue.core.dict.HttpMethod;
import com.blue.core.dict.annotation.DictParser;
import com.blue.http.annotation.Http;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.View;
import com.blue.http.message.ViewBuilder;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.core.facade.AreaFacade;
import com.web.base.core.message.AreaRequest;
import com.web.base.core.message.AreaResponse;
import com.web.core.async.redis.CacheRefreshSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller("coreAreaController")
@Http(url = "/base/core")
public class AreaController
{
	@Autowired
	private AreaFacade areaFacade;
	@Resource
	private CacheRefreshSender cacheRefreshSender;
	
	private DictParser dictParser = DictParser.getInstance();
	
	public AreaController()
	{
	}
	
	@Http(url = "/area_list", method = HttpMethod.GET)
	public View listGet(HttpRequest request)
	{
		AreaRequest areaRequest = request.getQueryObject(AreaRequest.class);
		return View.createBuilder().setView("/base/core/area_list")
				.put("map", dictParser.getStringMap())
				.put("model", areaRequest)
				.put("treeList", areaFacade.listTree(areaRequest))
				.build();
	}
	
	@Http(url = "/area_get", method = HttpMethod.GET)
	public View get(HttpRequest request)
	{
		AreaRequest areaRequest = request.getQueryObject(AreaRequest.class);
		AreaResponse areaResponse = null;
		if (areaRequest.getId() != null)
		{
			areaResponse = areaFacade.get(areaRequest.getId());
		}
		ViewBuilder builder = View.createBuilder();
		if (areaRequest.getParentId() != null)
		{
			builder.put("parentModel", areaFacade.get(areaRequest.getParentId()));
		}
		return builder.setView("/base/core/area_get")
				.put("map", dictParser.getStringMap())
				.put("model", areaResponse)
				.build();
	}
	
	@Http(url = "/area_save", method = HttpMethod.POST)
	public void save(HttpRequest request)
	{
		AreaRequest areaRequest = request.getPostObject(AreaRequest.class);
		if (areaRequest.getId() == null)
		{
			ValidationUtil.valid(areaRequest, SaveModel.class);
			areaFacade.add(areaRequest);
		}
		else
		{
			ValidationUtil.valid(areaRequest, UpdateModel.class);
			areaFacade.update(areaRequest);
		}
	}

	@Http(url = "/area_refresh", method = HttpMethod.POST)
	public void refresh(HttpRequest request)
	{
		areaFacade.refresh();
	}
	
}
